﻿/*
Copyright (C) 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

function UI() {
}

UI.ITEM_BACKGROUND_NORMAL = 'images/bg_row.png';
UI.ITEM_BACKGROUND_HOVER = 'images/bg_row_blue.png';


UI.ITEM_BGCOLOR_NORMAL = 'white';
UI.ITEM_BGCOLOR_HOVER = 'blue';


UI.NORMAL_TEXT_COLOR = '#000000';
UI.GREEN_TEXT_COLOR = '#007000';
UI.RED_TEXT_COLOR = '#900000';
UI.HEADER_TEXT_COLOR = '#6F6F6F';

UI.MIN_HEIGHT = 53;
UI.MIN_LISTBOX_WIDTH = 198;
UI.UNDOCKED_WIDTH = UI.MIN_LISTBOX_WIDTH + 2;

UI.DEFAULT_FONT = 'Tahoma';

UI.WIDTH_PCT = '17%'; //1 / col count 

UI.appendHeader = function(div, text, x, align) {
  var label = div.appendElement('<label />');
  label.font = UI.DEFAULT_FONT;
  label.size = 8;
  label.height = '100%';
  // Each column gets equal width.
  label.width = UI.WIDTH_PCT;
  label.align = align;
  label.color = UI.HEADER_TEXT_COLOR;
  label.bold = true;
  label.enabled = false;
  label.innerText = text;
  label.x = x;

  return label;
};

UI.appendColumn = function(security, div, isBold, color) {
    var label = div.appendElement('<label />');
    label.font = UI.DEFAULT_FONT;
    label.size = 8;
    label.height = '100%';
    // Each column gets equal width.
    label.width = UI.WIDTH_PCT;
    label.align = 'right';
    label.color = UI.NORMAL_TEXT_COLOR;
    label.bold = isBold;
    label.color = color || UI.NORMAL_TEXT_COLOR;

    label.enabled = true;
    label.onmouseover = UI.handleMouseOver;
    label.onmouseout = UI.handleMouseOut;
    label.onclick = function(security) {
        return function() {
            openDetails(security);
        };
    } (security);
    label.ondblclick = function(id) {
        return function() {
            openInBrowser(id);
        };
    } (security.getId());

    return label;
};

UI.draw = function(securities) {
    /*    
    if (loadingLabel.visible)
    loadingLabel.visible = false;
  
if(btnResetOptions.visible)
    btnResetOptions.visible = false;
    */

    listbox.removeAllElements();

    var headers = listbox.appendElement('<listitem />');
    var headersDiv = headers.appendElement('<div />');
    headersDiv.width = '100%';
    headersDiv.height = '100%';
    headersDiv.x = 0;
    headersDiv.y = 0;

    headersDiv.background = UI.ITEM_BACKGROUND_NORMAL;

    var left0 = '0';
    var left1 = '50';
    var left2 = '95';
    var left3 = '145';
    var left4 = '190';
    var left5 = '240';

    UI.appendHeader(headersDiv, 'Name', left0, 'left');
    UI.appendHeader(headersDiv, '%', left1, 'center');

    UI.appendHeader(headersDiv, '%2S', left2, 'right');
    UI.appendHeader(headersDiv, '%2R', left3, 'right');


    UI.appendHeader(headersDiv, 'Price', left4, 'right');
    UI.appendHeader(headersDiv, 'Change', left5, 'right');

    for (var i = 0; i < securities.length; ++i) {
        var security = securities[i];

        var listitem = listbox.appendElement('<listitem />');

        var div = listitem.appendElement('<div />');
        div.width = '100%';
        div.height = '100%';
        div.x = 0;
        div.y = 0;


        var isBold = false; // bold is annoying and taks up more space -- security.isLargeMove();

        var color = UI.NORMAL_TEXT_COLOR;

        var last = security.last;
        var change = security.change;
        var changePercent = security.changePercent;


        if (security.isAfterHours()) {
            last = security.extendedLast;
            change = security.extendedChange;
            changePercent = security.extendedChangePercent;
            isBold = security.isExtendedLargeMove();
        }

        if (change > 0) {
            color = UI.GREEN_TEXT_COLOR;
        } else if (change < 0) {
            color = UI.RED_TEXT_COLOR;
        }

        var tickerColumn = UI.appendColumn(security, div, isBold, color);
        tickerColumn.align = 'left';
        tickerColumn.innerText = security.getDisplayName();
        tickerColumn.tooltip = security.name;
        tickerColumn.width = '' + (left1 - left0) + '';

        var afterHoursIcon = div.appendElement('<img name="afterHoursIcon" />');
        afterHoursIcon.x = 33;
        afterHoursIcon.y = 2;
        afterHoursIcon.src = 'images/after_hours.png';
        afterHoursIcon.visible = security.isAfterHours();
        afterHoursIcon.tooltip = security.name;


        if (security.isLargeMove() || (security.isAfterHours() && security.isExtendedLargeMove())) {
            var div2 = div.appendElement('<div />');
            div2.width = '' + (left1 - left0) + '';
            div2.height = '100%';
            div2.x = left1;
            div2.y = 0;
            div2.background = 'lightyellow';
        }

        var changePercentColumn = UI.appendColumn(security, div, security.isLargeMove(), color);
        changePercentColumn.innerText = changePercent + '%';
        changePercentColumn.x = left1;
        changePercentColumn.tooltip = security.name;
        changePercentColumn.width = '' + (left2 - left1) + '';

        if (!infosParsed) {
            LoadInfos();
        }
        info = g_securityInfos[security.ticker];
        info.security = security;

        /*
        var div2 = div.appendElement('<div />');
        div2.width = '100%';
        div2.height = '100%';

        div2.background = 'lightblue';
        */

        var suppResistNote = info.support + ' - ' + info.resistance + '  (' + security.last + ')';

        var pct = info.PercentOffSupport(parseFloat(last.replace(",", "")));

        var pctSign = '%';

        if (pct == Number.POSITIVE_INFINITY || pct == Number.NEGATIVE_INFINITY) {
            pct = '';
            pctSign = '';
        }
        else {
            var div2 = div.appendElement('<div />');
            div2.width = '' + (left3 - left2) + '';
            div2.height = '100%';
            div2.x = left2;
            div2.y = 0;
            div2.background = PctOffToColor(pct, info.lastWarnPct);
        }


        var lastColumn = UI.appendColumn(security, div, pct < 10, 'black');
        lastColumn.innerText = pct + pctSign; //        info.support;
        lastColumn.x = left2;
        lastColumn.tooltip = suppResistNote;
        lastColumn.width = '' + (left3 - left2) + '';


        var pct = info.PercentOffResistance(parseFloat(last.replace(",", "")));

        pctSign = '%';
        if (pct == Number.POSITIVE_INFINITY || pct == Number.NEGATIVE_INFINITY) {
            pct = '';
            pctSign = '';
        }
        else {
            var div2 = div.appendElement('<div />');
            div2.width = '' + (left4 - left3) + '';
            div2.height = '100%';
            div2.x = left3;
            div2.y = 0;
            div2.background = PctOffToColor(pct, info.lastWarnPct);
        }

        var lastColumn = UI.appendColumn(security, div, pct < 10, 'black');
        lastColumn.innerText = pct + pctSign; // info.resistance;
        lastColumn.x = left3;
        lastColumn.tooltip = suppResistNote;
        lastColumn.width = '' + (left4 - left3) + '';



        var lastColumn = UI.appendColumn(security, div, isBold, color);
        lastColumn.innerText = Util.trimDecimalDigitsIfGe1000(last);
        lastColumn.x = left4;
        lastColumn.tooltip = security.name;

        var changeColumn = UI.appendColumn(security, div, isBold, color);
        changeColumn.innerText = change;
        changeColumn.x = left5;
        changeColumn.tooltip = security.name;

    }


    if (!g_isDocked) {
        UI.setUndockedHeight();
    }

    //g_securityInfos.sort(sortByPctOff);


    var secsSinceLastMsg = (new Date().getTime() - lastMsgMS) / 1000;
    var today = new Date().getDate();

    for (key in g_securityInfos) {
        var msg = '';

        var info = g_securityInfos[key];
        var mpct = info.MinPercentOff();

        //only warn once per threshhold per day
        var warn = (info.lastWarnDay != today)
                || Math.round(mpct) < info.lastWarnPct;

        var reverse = false;
        var ud = (mpct == info.lastPctOffSupport  ? '▼' : '▲');
        
        if (mpct > info.lastWarnPct + 2) {
            //reset the pct if there's a 5% move
            //so there will be another warning as the pct is reduced

            info.lastWarnPct = mpct;
            warn = true;
            reverse = true;

            ud = (mpct == info.lastPctOffSupport ? '▲' : '▼');
        }

        if (mpct < 25 && warn && !(Number.NEGATIVE_INFINITY == mpct)) {

            var sr = ud + (info.lastPctOffSupport == mpct ? "S" : "R") + ud;

            msg += info.ticker + ': ' + sr + '$' + info.security.last + '   ' + mpct + '% ';

            info.lastWarnDay = today;
            info.lastWarnPct = Math.round(mpct);
        }

        if (msg != '') {
            showStockAlert(msg);
        }

    }



}


function showStockAlert(msg) {

    if (msg != '') {

        var now = new Date();

        var h = now.getHours() % 12;

        if (h == 0) {
            h == 12;
        }

        var time = h + ":" + right('0' + now.getMinutes(), 2) + ":" + right('0' + now.getSeconds(), 2);

        lastMsgMS = new Date().getTime();

        Notify(msg, time );
    }
}

function right(s, n) {

    
    if (n <= 0)
        return "";
    else if (n > s.length)
        return s;
    else {
        var iLen = s.length;
                
        return s.substr(iLen - n, n);
    }


}

var lastMsgMS = 0;

function sortByPctOff(a, b) {
    //Compare "a" and "b" in some fashion, and return -1, 0, or 1

    var minA = a.MinPercentOff();
    var minB = b.MinPercentOff();

    return a < b ? 1 : ((a == b) ? 0 : -1);
}

function Notify(head, msg) {
    var item = new ContentItem();
    item.heading = head;
    item.snippet = msg;
    //item.flags = gddContentItemFlagHtml;
    plugin.removeAllContentItems();
    plugin.AddContentItem(item, gddItemDisplayAsNotification);
}

function PctOffToColor(pct, lastMin) {

    //green means action happened

    /*
        //needs work:
    //the stock has bounced off -- could be a support or resistance
    if (pct > lastMin + 2) {
    return 'green';
    }
    */
    if (pct > 25) {
        return 'white';
    }

    if (pct > 7) {
        return 'yellow';
    }

    if (pct > 3) {
        return 'orange';

    }

    if (pct > -1) {
        return 'red';
    }

    //gone through -- either support or resistance
    return 'green';
}


UI.handleMouseOut = function() {
			event.srcElement.parentElement.background = UI.ITEM_BACKGROUND_NORMAL;
};




UI.handleMouseOver = function() {

  event.srcElement.parentElement.background = UI.ITEM_BACKGROUND_HOVER;
};

UI.setUndockedHeight = function() {
  if (upgradeDiv.visible) {
    listboxContainer.height = upgradeInfoUrl.y + upgradeInfoUrl.height;
  } else {
    listboxContainer.height = listbox.children.count * listbox.itemHeight;

    if (listboxContainer.height < listbox.itemHeight) {
      listboxContainer.height = 64;
    }
  }

  view.height = listboxContainer.y + listboxContainer.height +
      bottommiddle.height;
};

UI.getMaxHeight = function() {
  return listboxContainer.y + listbox.children.count * listbox.itemHeight +
      bottommiddle.height;
};

UI.resize = function() {
  topright.x = view.width - topright.width;
  topmiddle.width = view.width - topleft.width - topright.width;
  toplefttitle.width = topmiddle.width - topleftlogo.width;

  listboxContainer.y = topmiddle.height;
  listboxContainer.height = view.height - bottommiddle.height -
      listboxContainer.y;

  middleLeft.y = topmiddle.height;
  middleRight.y = topmiddle.height;
  middleRight.x = view.width - middleRight.width;

  var middleHeight = listboxContainer.height;
  middleLeft.height = middleHeight;
  middleRight.height = middleHeight;

  listboxContainer.width = view.width - 2;
  listbox.width = listboxContainer.width;
  if (listbox.width < UI.MIN_LISTBOX_WIDTH) {
    listbox.width = UI.MIN_LISTBOX_WIDTH;
  }
  listboxContainer.x = 1;

////    if (loadingLabel.width)
////  loadingLabel.width = view.width - 2;
////  
//  if(loadingLabel.x )
//  loadingLabel.x = 1;

  var bottomY = listboxContainer.y + listboxContainer.height;
  bottomleft.y = bottomY;
  bottommiddle.y = bottomY;
  bottomright.y = bottomY;
  grippy.y = bottomY;
  optionsButton.y = bottomY + 1;

  bottomright.x = view.width - bottomright.width;
  grippy.x = bottomright.x - grippy.width;
  bottommiddle.width = view.width - bottomleft.width - bottomright.width;
};

